<script setup lang="ts">
import { ref, nextTick, type Ref } from 'vue'
import $ from 'jquery'

import readsql from '../utils/ReadSql'
import ctrlsql from '../utils/ControlSql'

import BaseFrame from '../components/BaseFrame.vue'
import ManagerPanel from '../components/icons/ManagerPanel.vue'
import InputPanel from '../components/icons/InputPanel.vue'

const block_margin_left = ref('256')
const block_width = ref('1200')

interface BlockFormData {
  margin_left: string,
  width: string
}
const getBlockForm = (data: BlockFormData) => {
  block_margin_left.value = data.margin_left
  block_width.value = data.width
  console.log(data)
}

const showDiv = ref(0)
const addModel = ref(false)
const addConfirmStyle = ref('primary')

// for subdom managerpanel
const title = '管理员'
const table_name = 'Administrator'
const page_title = ref('系统管理员管理')
const table_labels = ['id', 'username', 'nickname', 'permission_key', 'restricted']
const table_display_names = ['编号', '用户名', '昵称', '根管理员', '是否被封禁']
const table_data: Array<any> = []
const table_data_format: Array<Array<string>> = [
  ['permission_key', 'is_ornot'],
  ['restricted', 'is_ornot'],
]
const ctrl_btn = ['delete', 'edit', 'restricted']
const ctrl_url = {
  base: '/api/sql-deal',
  restrict: '/api/admins/lock',
}
const detail_labels = ['id', 'username', 'nickname', 'email', 'phonenumber', 'permission_key', 'restricted']
const detail_display_names = ['编号', '用户名', '昵称', '邮箱', '手机号码', '权限（根管理员）', '账户锁定']
const detail_label_options = new Map([
  ['permission_key', 'is_ornot'],
  ['restricted', 'is_ornot'],
  ['phonenumber', 'obj_msg'],
  ['email', 'obj_msg'],
])

// for subdom inputpanel
const inputListLabels = ['username', 'nickname', 'permission']
const inputListTypes = ['text', 'text', 'select']
const inputListOptions = new Map([
  [2, {
    select_options: [
      {
        label: 'root',
        value: '0',
      },
      {
        label: 'non root',
        value: '1',
      }
    ]
  }]
])
const inputListRef: Ref<string[]> = ref([])
for (var idx = 0; idx < inputListLabels.length; idx += 1)
  inputListRef.value.push('')

// to subdom managerpanel edit model
const editKeyTypes = ['string', 'string', 'number']
const editListLabels = ['username', 'nickname', 'permission_key']
const editListTypes = ['text', 'text', 'select']
const editListOptions = new Map([
  [2, {
    select_options: [
      {
        label: 'root',
        value: '0',
      },
      {
        label: 'non root',
        value: '1',
      }
    ]
  }]
])
const edit_options = {
  editKeyTypes,
  editListLabels,
  editListTypes,
  editListOptions,
}

// property processing: get amdins message
readsql.readSQL({
  table: 'Administrator',
  keys: table_labels,
  key_types: ['', '', '', ''],
  where: null,
  where_key: null,
  group_by_keys: null,
  order_by_keys: null,
  limit: null,
}).then((res) => {
  // res['data']['data'][0] the results format getter
  for (var idx = 0; idx < res['data']['data'].length; idx += 1) {
    table_data.push(res['data']['data'][idx])
  }
  nextTick(() => { showDiv.value += 1 })
})

const showAddModel = () => {
  addConfirmStyle.value = 'primary'
  $('#admin-add-confirm').text('确定')
  for (var idx = 0; idx < inputListRef.value.length; idx += 1) {
    inputListRef.value[idx] = ''
  }
  addModel.value = true
}

const addToSQL = () => {
  let allow = true
  console.log(allow)
  for (var idx = 0; idx < inputListRef.value.length; idx += 1) {
    if (inputListRef.value[idx] == null || inputListRef.value[idx] == '') {
      allow = false
      break
    }
  }
  if (allow) {
    inputListLabels[2] = 'permission_key'
    inputListLabels.push('password')
    inputListRef.value.push('123456')
    var keyTypes = ['string', 'string', 'number', 'string']

    ctrlsql.ctrlSQL({
      method: 'insert',
      table: 'Administrator',
      keys: inputListLabels,
      key_types: keyTypes,
      values: inputListRef.value,
      where: null,
      where_key: null,
      group_by_keys: null,
      order_by_keys: null,
      limit: null,
    }).then((res) => {
      if (res['data']['ok']) {
        setTimeout(() => {
          addConfirmStyle.value = 'success'
          $('#admin-add-confirm').text('添加成功')
          addModel.value = false
        }, 3000)
      } else {
        addConfirmStyle.value = 'danger'
        $('#admin-add-confirm').text('添加失败，数据处理层错误')
      }
      inputListLabels[2] = 'permission'
      inputListLabels.pop()
      inputListRef.value.pop()
      nextTick(() => { /* showDiv.value += 1 */ location.reload() })
    })
  } else {
    addConfirmStyle.value = 'danger'
    $('#admin-add-confirm').text('请完善信息')
  }
}

</script>

<template>
  <BaseFrame :page_title="page_title" @get-block-form_="getBlockForm"/>
  <div class="block__" :style="{ marginLeft: block_margin_left + 'px', width: block_width, transition: '0.34s'}">
    <el-button type="primary" style="margin-bottom: 3px;" @click="showAddModel()" plain>添加管理员</el-button>
    <ManagerPanel :key="showDiv" :title="title" :table_data="table_data" :table_labels="table_labels"
      :table_name="table_name" :ctrl_url="ctrl_url" :table_display_names="table_display_names"
      :table_data_format="table_data_format" :ctrl_btn="ctrl_btn" :edit_options="edit_options"
      :detail_labels="detail_labels" :detail_label_options="detail_label_options"
      :detail_display_names="detail_display_names" />
  </div>

  <el-dialog v-model="addModel" title="添加管理员" width="40%">
    <InputPanel :input-list-labels="inputListLabels" :input-list-types="inputListTypes" :input-list-ref="inputListRef"
      :input-list-options="inputListOptions" />
    <template #footer>
      <span class="model-footer">
        <el-button @click="addModel = false">取消</el-button>
        <el-button @click="addToSQL()" :type="addConfirmStyle" id="admin-add-confirm">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style lang="scss">
.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>